package com.example.rabc.monitor;

import com.sun.management.OperatingSystemMXBean;
import org.springframework.stereotype.Component;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadMXBean;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 系统指标采集器
 */
@Component
public class SystemMetricsCollector {
    private final MonitorEventBus eventBus; // 监控事件总线
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2); // 定时任务执行器

    /**
     * 构造函数，初始化系统指标采集器
     * @param eventBus 监控事件总线，用于通知采集到的指标
     */
    public SystemMetricsCollector(MonitorEventBus eventBus) {
        this.eventBus = eventBus;
        // 定时采集系统指标
        scheduler.scheduleAtFixedRate(this::collectSystemMetrics, 0, 10, TimeUnit.SECONDS); // 每10秒采集一次系统指标
    }

    /**
     * 采集系统指标并通知事件总线
     */
    private void collectSystemMetrics() {
        Map<String, Object> metrics = new HashMap<>(); // 采集到的系统指标
        
        try {
            // CPU使用率
            OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
            metrics.put("cpuUsage", Math.max(0, osBean.getProcessCpuLoad() * 100));// 进程CPU使用率
            
            // 内存使用情况
            MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); // 内存管理MXBean
            MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();// 堆内存使用情况
            metrics.put("heapUsed", heapUsage.getUsed());// 堆内存已用
            metrics.put("heapMax", heapUsage.getMax());// 堆内存最大
            if (heapUsage.getMax() > 0) {
                metrics.put("heapUsagePercent", (double) heapUsage.getUsed() / heapUsage.getMax() * 100);// 堆内存使用率
            }
            
            // JVM线程数
            ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); // 线程管理MXBean
            metrics.put("threadCount", threadBean.getThreadCount());// JVM线程数
            
            MonitorEvent event = new BaseMonitorEvent("SYSTEM_METRICS", metrics); // 系统指标监控事件
            eventBus.notifyObservers(event); // 通知事件总线采集到的系统指标
        } catch (Exception e) {
            // 记录采集错误但不影响主流程
            Map<String, Object> errorData = new HashMap<>();
            errorData.put("error", e.getMessage());
            MonitorEvent errorEvent = new BaseMonitorEvent("METRICS_COLLECTION_ERROR", errorData);
            eventBus.notifyObservers(errorEvent);
        }
    }
}